package lc20240425;

public class ReverseString {
    public static void main(String[] args) {
        String s = "Hello world dashda eqw   qweqw ";
        System.out.println("reverseWords(s) = " + reverseWords(s));
    }

    public static String reverseWords(String s) {
        s = s.trim();
        StringBuilder stringBuilder = new StringBuilder();
        int n = s.length();
        int i = n - 1;
        int j = n - 1;
        while (i>=0) {
            while (i>=0&&s.charAt(i)!=' ') {
                i--;
            }
            //找到第一个单词的起始位置。
            int wordEnd=i+1;
            stringBuilder.append(s, wordEnd, j+1);
            if (i>0) {
                stringBuilder.append(' ');
            }

            //移动j到下一个单词末尾
            while (i>=0&&s.charAt(i)==' '){
                i--;
            }
            j=i;
        }
        return stringBuilder.toString();
    }
}
